#ifndef IMAGEPROCESSOR_H
#define IMAGEPROCESSOR_H

#include <QObject>
#include <QByteArray>
#include <QMutex>

// FFmpeg库
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
}

class ImageProcessor : public QObject
{
    Q_OBJECT
public:
    explicit ImageProcessor(int width, int height, int fps, QObject *parent = nullptr);
    ~ImageProcessor() override;

    bool initEncoder(); //初始化软件编码器
    bool initHardwareEncoder_h264_nvenc(); //初始化h264_nvenc硬件编码器
    bool initHardwareEncoder_h264_vaapi();  //初始化h264_vaapi硬件编码器
    
signals:
    void frameEncoded(const QByteArray &data);
    void errorOccurred(const QString &errorString);
    
public slots:
    void onProcessImageData(const QByteArray &data);

    void onInitEncoder();
    
private:
    AVCodec *m_codec;
    AVCodecContext *m_codecCtx;
    AVFrame *m_frame;
    AVPacket *m_packet;
    QMutex m_mutex;
    int m_frameCount;
    
    bool convertToYUV420P(const QByteArray &grayData, AVFrame *frame);
    void gray16To8bit(const QByteArray &grayData, AVFrame *frame);

    bool encodeFrame(AVFrame *frame, QByteArray &outputData);

    int m_width;
    int m_height;
    int m_fps;
};

#endif // IMAGEPROCESSOR_H
